﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml;

namespace SF.WebClient
{
    public class Log4Config
    {
        /// <summary>
        /// 尝试创建日志文件夹
        /// </summary>
        public static void TryBuildLogFolder()
        {
            string pathBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string path = pathBase + @"\log4net.config";

            XmlDocument doc = new XmlDocument();
            try { doc.Load(path); }
            catch { throw new Exception("缺少log4net.config配置文件，请在启动项根目录中添加该配置文件。"); }

            //configuration
            XmlElement rootElem = doc.DocumentElement;
            if (rootElem == null) { throw new Exception("log4net.config配置文件中缺少根节点 configuration 的配置，请补全。"); }

            //log4net
            XmlNodeList log4netNodes = rootElem.GetElementsByTagName("log4net");
            if (log4netNodes.Count == 0) { throw new Exception("log4net.config配置文件中缺少 configuration 下的 log4net 配置节点，请补全。"); }

            //appender
            XmlNode appenderNode = null;
            XmlNodeList appenderNodes = log4netNodes[0].ChildNodes;
            for (int i = 0; i < appenderNodes.Count; i++)
            {
                XmlNode node = appenderNodes.Item(i);
                if (node.Name.Equals("appender"))
                { appenderNode = node; break; }
            }
            if (appenderNode == null)
            { throw new Exception("log4net.config配置文件中缺少 configuration/log4net 下的 appender 配置节点，请补全。"); }

            //file
            XmlNode fileNode = null;
            XmlNodeList fileNodes = appenderNode.ChildNodes;
            for (int i = 0; i < fileNodes.Count; i++)
            {
                XmlNode node = fileNodes.Item(i);
                if (node.Name.Equals("file"))
                { fileNode = node; break; }
            }
            if (fileNode == null)
            { throw new Exception("log4net.config配置文件中缺少 configuration/log4net/appender 下的 file 配置节点，该节点表示日志文件相对于项目根目录的相对路径，请补全。"); }

            string filePath = (fileNode as XmlElement).GetAttribute("value");
            if (!string.IsNullOrWhiteSpace(filePath) && filePath.Contains(@"\"))
            {
                string folderPath = pathBase + @"\" + filePath;
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }
            }
        }
    }
}